package com.nais.controllers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.nais.constant.OrderSource;
import com.nais.constant.OrderStatus;
import com.nais.constant.OrderType;
import com.nais.domain.EcCourse;
import com.nais.domain.EcCourseArrange;
import com.nais.domain.EcCourseArrangeCriteria;
import com.nais.domain.MainOrder;
import com.nais.domain.OrderCourse;
import com.nais.mapper.EcCourseArrangeMapper;
import com.nais.mapper.EcCourseMapper;
import com.nais.mapper.MainOrderMapper;
import com.nais.mapper.OrderCourseMapper;
import com.nais.service.UserInfoService;
import com.nais.vo.CourseChoiseVo;
import com.nais.vo.UserFullInfo;

@Controller
@RequestMapping("course")
public class CourseChoiseController implements InitializingBean{

	
	@Autowired
	private EcCourseMapper ecCourseMapper;
	
	@Autowired
	private EcCourseArrangeMapper ecCourseArrangeMapper;
	
	@Autowired
	private MainOrderMapper mainOrderMapper;
	
	@Autowired
	private OrderCourseMapper orderCourseMapper;
	
	@Autowired
	private UserInfoService userInfoService;
	
	private static final Map<Integer, Long> priceMap = new ConcurrentHashMap<>();
	
	@Override
	public void afterPropertiesSet() throws Exception {
		priceMap.put(1, 15790L);
		priceMap.put(2, 25790L);
		priceMap.put(3, 35790L);
		priceMap.put(4, 45790L);
	}
	
	@GetMapping("choose/{schoolId}")
	public String courseChoose(Model model , @PathVariable("schoolId")Integer schoolId){
		
		schoolId = schoolId == null ? 0 : schoolId;
		
		EcCourseArrangeCriteria ecCourseArrangeCriteria = new EcCourseArrangeCriteria();
		
		ecCourseArrangeCriteria.createCriteria().andSidEqualTo(schoolId);
		
		List<EcCourseArrange> arrangeList = ecCourseArrangeMapper.selectByExample(ecCourseArrangeCriteria);
	
		Map<String, List<CourseChoiseVo>> arrangeMap = new HashMap<>(); 
		
		if (CollectionUtils.isNotEmpty(arrangeList)) {
			
			for (EcCourseArrange arrange : arrangeList) {
					
				CourseChoiseVo vo = makeCourseChoiseVo(arrange);
			
				String timeString = StringUtils.join(Arrays.asList(vo.getCourseTimeStart(), vo.getCourseTimeEnd()), "~");
				
				if (!arrangeMap.containsKey(timeString)) {
					List<CourseChoiseVo> choiseList = new ArrayList<>();
					choiseList.add(vo);
					arrangeMap.put(timeString, choiseList);
				}else {
					arrangeMap.get(timeString).add(vo);
				}
			}
			
		}
		
		model.addAttribute("courseMap", arrangeMap);
		return "corse-choose";
	}

	
	@PostMapping("validate/{arrangIds}")
	@ResponseBody
	public JSONObject validate(@PathVariable("arrangIds")String arrangIds){
		
		JSONObject json = new JSONObject();
		boolean result = true;
		
		if (StringUtils.isBlank(arrangIds)) {
			json.put("result", false);
			json.put("msg", "传入的课程有误");
			return json;
		}
		
		String[] arrangIdArr = arrangIds.split(",");
		
		List<Integer> arrangIdList = new ArrayList<>();
		
		for (String arrangIdStr : arrangIdArr) {
			arrangIdList.add(Integer.valueOf(arrangIdStr));
		}
		
		EcCourseArrangeCriteria arrangeCriteria = new EcCourseArrangeCriteria();
		arrangeCriteria.createCriteria().andIdIn(arrangIdList);
		
		
		List<EcCourseArrange> arrangeList = ecCourseArrangeMapper.selectByExample(arrangeCriteria);
		
		if (CollectionUtils.isEmpty(arrangeList)) {
			json.put("result", false);
			json.put("msg", "传入的课程有误");
			return json;
		}
		
		Set<String> timeSet = new HashSet<>();
		
		for (EcCourseArrange arrange : arrangeList) {				
			
			if (timeSet.contains(arrange.getBeginTime())) {
				result = false;
				json.put("msg", "课程时间冲突");
				break;
			}
			timeSet.add(arrange.getBeginTime());
		}
		
		json.put("result", result);
		return json;
		
	}
	
	
	@GetMapping("submitCourse")
	public String submitCourse(Model model , @RequestParam("arrangIds")String arrangIds){
		
		if (StringUtils.isNotBlank(arrangIds)) {
			
			String[] arrangIdArr = arrangIds.split(",");
			
			Set<String> timeSet = new HashSet<>();
			
			List<CourseChoiseVo> courseVoList = new ArrayList<>();
			
			List<Integer> arrangIdList = new ArrayList<>();
			
			for (String arrangIdStr : arrangIdArr) {
				arrangIdList.add(Integer.valueOf(arrangIdStr));
			}
			
			EcCourseArrangeCriteria arrangeCriteria = new EcCourseArrangeCriteria();
			arrangeCriteria.createCriteria().andIdIn(arrangIdList);
			
			List<EcCourseArrange> arrangeList = ecCourseArrangeMapper.selectByExample(arrangeCriteria);
			
			if (CollectionUtils.isEmpty(arrangeList)) {
				return "";
			}
			
			for (EcCourseArrange arrange : arrangeList) {				
				
				if (timeSet.contains(arrange.getBeginTime())) {
					break;
				}
				timeSet.add(arrange.getBeginTime());
				
				CourseChoiseVo vo = makeCourseChoiseVo(arrange);
				courseVoList.add(vo);
			}
			
			model.addAttribute("courseVoList", courseVoList);
			model.addAttribute("totalPrice", priceMap.get(arrangIdArr.length));
		}
		return "order-preview";
	}

	//需要提供下个跳转页信息
	@GetMapping("saveOrder")
	public String saveOrder(Model model , @RequestParam("arrangIds")String arrangIds){
		
		if (StringUtils.isNotBlank(arrangIds)) {
			
			String[] arrangIdArr = arrangIds.split(",");
			
			Set<String> timeSet = new HashSet<>();
			
			Long campusId = 0L;

			List<Integer> arrangIdList = new ArrayList<>();
			
			for (String arrangIdStr : arrangIdArr) {
				arrangIdList.add(Integer.valueOf(arrangIdStr));
			}
			
			EcCourseArrangeCriteria arrangeCriteria = new EcCourseArrangeCriteria();
			arrangeCriteria.createCriteria().andIdIn(arrangIdList);
			
			List<EcCourseArrange> arrangeList = ecCourseArrangeMapper.selectByExample(arrangeCriteria);
			
			if (CollectionUtils.isEmpty(arrangeList)) {
				return "step4-pay";
			}
			
			List<OrderCourse> orderCourseList = new ArrayList<>();
			
			for (EcCourseArrange arrange : arrangeList) {
				campusId = Long.valueOf(arrange.getCid());
				
				if (timeSet.contains(arrange.getBeginTime())) {
					return "step4-pay";
				};
				timeSet.add(arrange.getBeginTime());
				
				OrderCourse orderCourse = new OrderCourse();
				orderCourse.setSchoolId(Long.valueOf(arrange.getSid()));
				orderCourse.setCourseId(Long.valueOf(arrange.getCid()));
				orderCourse.setArrangeId(Long.valueOf(arrange.getId()));
				orderCourse.setCreateTime(new Date());
				orderCourse.setUpdateTime(new Date());
			
				orderCourseList.add(orderCourse);
			}
			
			MainOrder mainOrder = new MainOrder();
			mainOrder.setPaymentSeq(createPaymentSeq());
			mainOrder.setOrderVersion(1);
			mainOrder.setOrderStatus(OrderStatus.CREATE.getIndex());
			mainOrder.setOrderSource(OrderSource.SUMMER_SCHOOL.getIndex());
			mainOrder.setOrderType(OrderType.S_XUANKE.getIndex());
			
			Long cashAmount = priceMap.get(arrangeList.size());
			
			mainOrder.setOrderCampus(campusId);
			mainOrder.setTotalAmount(cashAmount);
			mainOrder.setCashAmount(cashAmount);
			
			mainOrder.setCreateTime(new Date());
			mainOrder.setUpdateTime(new Date());
			
			mainOrderMapper.insertSelective(mainOrder);
			model.addAttribute("orderId", mainOrder.getId());
			model.addAttribute("paymentSeq", mainOrder.getPaymentSeq());
			
			saveOrderCourses(mainOrder.getId(), orderCourseList);
			
		}
		return "step4-pay";
	}
	
	private void saveOrderCourses(Long orderId, List<OrderCourse> orderCourses){
		for (OrderCourse orderCourse : orderCourses) {
			orderCourse.setOrderId(orderId);
			orderCourseMapper.insertSelective(orderCourse);
		}
	}
	
	
	private static String createPaymentSeq(){
		
		return String.format("SSXK%s", new Date().getTime());
		
	}

	private CourseChoiseVo makeCourseChoiseVo(EcCourseArrange arrange) {

		CourseChoiseVo vo = new CourseChoiseVo();
		vo.setCourseArrangeId(Long.valueOf(arrange.getId()));
		vo.setCourseTimeStart(arrange.getBeginTime());
		vo.setCourseTimeEnd(arrange.getEndTime());
		vo.setCourseClass(arrange.getBeginTime().replace(":", ""));
		
		EcCourse couese = ecCourseMapper.selectByPrimaryKey(arrange.getCid());

		if (couese != null) {
			vo.setCourseName(couese.getTitle());
			vo.setCourseCode(couese.getCode());
		}

		UserFullInfo userInfo = userInfoService.getUserFullInfoById(arrange.getTid());

		if (userInfo != null) {
			vo.setTeacherFirstName(userInfo.getUsers().getFirstName());
			vo.setTeacherFirstName(userInfo.getUsers().getLastName());
			vo.setTeacherSchoolName(userInfo.getUserInfo().getToSchool());
		}

		return vo;
	}


}
